package com.joyxuan.weixin;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.joyxuan.common.info.weixin.WeixinHelper;
import com.joyxuan.common.info.weixin.message.MediaMessageItem;
import com.joyxuan.common.info.weixin.message.MediaMessageTemplate;
import com.joyxuan.common.info.weixin.tag.Tag;
import com.joyxuan.common.info.weixin.tag.TagGet;
import com.joyxuan.common.info.weixin.user.UserInfo;
import com.joyxuan.common.utile.DesUtil;
import com.joyxuan.common.utile.JsonUtils;
import com.joyxuan.common.utile.LogUtil;
import com.joyxuan.common.utile.RedissonUtils;
import com.joyxuan.common.utile.ResultForm;
import com.joyxuan.common.utile.TimeUtil;
import com.joyxuan.core.member.dao.UserAccountDao;
import com.joyxuan.core.member.po.UserAccount;
import com.joyxuan.core.redpacket.po.RedPacket;
import com.joyxuan.core.redpacket.vo.SendRedPackeForm;
import com.joyxuan.core.wechat.dao.WechatActivityDao;
import com.joyxuan.core.wechat.dao.WechatGroupDao;
import com.joyxuan.core.wechat.dao.WechatUserDao;
import com.joyxuan.core.wechat.po.WechatActivity;
import com.joyxuan.core.wechat.po.WechatGroup;
import com.joyxuan.core.wechat.po.WechatUser;
import com.joyxuan.core.wechat.service.WechatActivityService;
import com.joyxuan.core.wechat.service.WechatUserService;
import com.joyxuan.core.wechat.vo.ActivityPacketRecordForm;
import com.joyxuan.weixin.constants.WebConstant;
import com.joyxuan.weixin.friends.vo.Member;
import com.joyxuan.weixin.mp.TokenGetter;
import com.ring.smc.framework.web.view.easyui.model.DataGridModel;

@RequestMapping("/activity")
@Controller
public class ActivityController extends CommonController {

	@Autowired
	private WechatActivityService wechatActivityService;
	@Autowired
	private WechatUserService wechatUserService;

	@Autowired
	private WechatGroupDao wechatGroupDao;

	@Autowired
	private WechatActivityDao wechatActivityDao;

	@Autowired
	private UserAccountDao accountDao;

	private final String ACTIVITY_PERSONS_KEY = "ACTIVITY_PERSONS_KEY_";
	
	private final String ACTIVITY_PERSONS_FILTER = "ACTIVITY_PERSONS_FILTER_";

	/**
	 * 清除微信公众号所有标签
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/mgrWxGroupDel")
	@ResponseBody
	public String mgrWxGroupDel(HttpServletRequest request) {
		if (!"qwertyuyasdmasbnbzxcxvmncxzmvsdfjcvnc34823684723czxmc".equals(request.getParameter("s"))) {
			return "error";
		}
		TagGet tagGet = WeixinHelper.tag.get(TokenGetter.getAccessToken());
		List<Tag> tags = tagGet.getTags();
		for (Tag tag : tags) {
			WeixinHelper.tag.delete(TokenGetter.getAccessToken(), tag.getId());
		}
		return "success";
	}

	/**
	 * 分组
	 * 
	 * @param request
	 * @param id
	 * @param count
	 * @return
	 */
	@RequestMapping("/grouping")
	@ResponseBody
	public ResultForm grouping(HttpServletRequest request, Long id, int count, int groupNum) {
		try {
			wechatUserService.wechatUserAllot(count, groupNum, Integer.valueOf(id + ""), TokenGetter.getAccessToken());
			return ResultForm.OK();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultForm.ERROR();
		}

	}

	/**
	 * 活动列列表页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/activities")
	public String activities(HttpServletRequest request, Model model) {
		Map<String, Object> params = new HashMap<String, Object>();
		int pageNo = getPageNo(request);
		int pageSize = getPageSize(request);
		DataGridModel da = wechatActivityService.query(params, pageSize, pageNo);
		List<WechatActivity> activities = (List<WechatActivity>) da.getRows();
		for (WechatActivity wechatActivity : activities) {
			wechatActivity.setStartDateStr(TimeUtil.getYYYYMMDDHHMM(wechatActivity.getStartDate()));
			wechatActivity.setEndDateStr(TimeUtil.getYYYYMMDDHHMM(wechatActivity.getEndDate()));
		}
		model.addAttribute("dataList", da);// 数据列表
		model.addAttribute("pageNo", pageNo);// 当前页
		model.addAttribute("pageSize", pageSize);// 每页记录数
		model.addAttribute("totalPage", countTotalPage(da.getTotal(), pageSize));// 总页数
		return "friends/pc/activities";
	}

	/**
	 * 活动管理
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/activityManager")
	public String actvityManager(HttpServletRequest request, Long id, Model model) {
		request.setAttribute("id", id);
		int pageNo = getPageNo(request);
		int pageSize = getPageSize(request);
		DataGridModel da = wechatActivityService.groupListData(id, pageSize, pageNo);
		request.setAttribute("datas", da.getRows());
		// 分组数据
		List<ActivityPacketRecordForm> activityPacketRecordForms = wechatActivityService
				.activityRedPacketRecordData(id);
		// 未分组人数
		List<WechatUser> users = wechatUserService.ungrouped(id);
		model.addAttribute("count", users.size());
		// 活动信息
		WechatActivity activity = wechatActivityDao.getById(id);
		if (null == activity)
			throw new RuntimeException();
		model.addAttribute("activity", activity);
		// 享贝
		Member member = (Member) request.getSession().getAttribute(WebConstant.MEMBER);
		if (null == member) {
			return "redirect:/friends/goLogin";
		}
		if (StringUtils.isEmpty(member.getWxNickName()))
			member.setWxNickName(member.getMobile());
		UserAccount account = accountDao.getByUserId(member.getMemberId());
		model.addAttribute("account", account);
		model.addAttribute("member", member);
		model.addAttribute("actvityRedList", activityPacketRecordForms);
		model.addAttribute("pageNo", pageNo);// 当前页
		model.addAttribute("pageSize", pageSize);// 每页记录数
		model.addAttribute("totalPage", countTotalPage(da.getTotal(), pageSize));// 总页数
		return "friends/pc/activityManager";
	}

	/**
	 * 清除微信的标签
	 * 
	 * @param request
	 * @param activityId
	 * @return
	 */
	@RequestMapping("/cleanwxGroup")
	@ResponseBody
	public ResultForm cleanwxGroup(HttpServletRequest request, Long activityId) {
		try {
			ResultForm resultForm = wechatActivityService.cleanwxGroup(activityId);
			return resultForm;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultForm.ERROR("系统异常");
		}
	}

	/**
	 * 创建活动
	 * 
	 * @param request
	 * @param name
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/activityCreate", method = RequestMethod.POST)
	@ResponseBody
	public ResultForm activityCreate(HttpServletRequest request, String name, String startTime, String endTime,
			int count, int aroundCount) {
		try {
			return wechatActivityService.activityCreate(name, TokenGetter.getAccessToken(),
					TimeUtil.getDateByString(startTime), TimeUtil.getDateByString(endTime), count, aroundCount);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultForm.ERROR("系统异常");
		}
	}

	/**
	 * 发送活动红包
	 * 
	 * @param request
	 * @param size
	 * @param amount
	 * @return
	 */
	@RequestMapping(value = "/sendActivityPacket", method = RequestMethod.POST)
	@ResponseBody
	public ResultForm sendActivityPacket(HttpServletRequest request, SendRedPackeForm sendRedPackeForm, Long id,
			Long activityId) {
		try {
			Member member = (Member) request.getSession().getAttribute(WebConstant.MEMBER);
			if (null == member)
				return ResultForm.ERROR("未登录");
			sendRedPackeForm.setMemberId(Long.parseLong(member.getMemberId()));
			ResultForm form = wechatActivityService.sendActivityPacket(sendRedPackeForm, id);
			if (form.isOk()) { // 调用微信群发接口
				RedPacket redPacket = (RedPacket) form.getObject();
				String url = "http://test.wx.joyxuan.com/website/redPacket/redPacketInfo?redId="
						+ DesUtil.encrypt(redPacket.getId().toString()) + "&recomend=" + member.getMemberId();
				MediaMessageItem messageItem = new MediaMessageItem();
				messageItem.setAuthor("享选商城");
				messageItem.setContent("享选商城向您发送一个红包，点击领取");
				messageItem.setContent_source_url(url);
				String fileUrl = request.getSession().getServletContext().getRealPath("")
						+ "/resources/img/pc/252995354227461952.png";
				messageItem.setFile(new File(fileUrl));
				messageItem.setShow_cover_pic("0");
				messageItem.setTitle("享选商城活动红包");
				MediaMessageTemplate mediaMessageTemplate = new MediaMessageTemplate();
				mediaMessageTemplate.articles.add(messageItem);
				WechatGroup group = wechatGroupDao.getById(id);
				mediaMessageTemplate.setTagId(Long.parseLong(group.getGroupId().toString()));
				List<WechatUser> users = wechatUserService.getWechatUserList(Integer.valueOf(activityId + ""));
				for (WechatUser wechatUser : users) {
					mediaMessageTemplate.getOpenIds().add(wechatUser.getOpenid());
				}
				ResultForm msgStatus = WeixinHelper.messages.send(TokenGetter.getAccessToken(), mediaMessageTemplate);
				if (!msgStatus.isOk()) {
					LogUtil.error("发送微信图文消息失败");
				}
			}
			return form;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultForm.ERROR("系统异常");
		}
	}

	/**
	 * 活动红包发放记录
	 * 
	 * @param request
	 * @param activityId
	 * @return
	 */
	@RequestMapping("/activityRedPacketRecordData")
	@ResponseBody
	public ResultForm activityRedPacketRecordData(HttpServletRequest request, Long activityId) {
		try {
			List<ActivityPacketRecordForm> activityPacketRecordForms = wechatActivityService
					.activityRedPacketRecordData(activityId);
			return ResultForm.OK().setObject(activityPacketRecordForms);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultForm.ERROR("系统异常");
		}

	}

	/**
	 * 跳至抽奖页面
	 * 
	 * @param request
	 * @param activityId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/lottery")
	public String lottery(HttpServletRequest request, String activityId, Model model) {
		model.addAttribute("activityId", activityId);
		return "friends/pc/lottery";
	}

	/**
	 * 抽奖获取微信用户列表
	 * 
	 * @param request
	 * @param activityId
	 * @return
	 */
	@RequestMapping("/getWechatUserList")
	@ResponseBody
	public ResultForm getWechatUserList(HttpServletRequest request, int activityId) {
		try {
			//过滤抽奖人
			Map<String, Object> filter = (Map<String, Object>) RedissonUtils.getRBucket(ACTIVITY_PERSONS_FILTER + activityId).get();
			if (null == filter) {
				filter = new HashMap<String, Object>();
			}
			//中奖人
			WechatUser returnUser = null;
			// TODO 待优化  参加活动的人
			List<WechatUser> ac = (List<WechatUser>) RedissonUtils.getRBucket(ACTIVITY_PERSONS_KEY + activityId).get();
			if (CollectionUtils.isEmpty(ac)) {
				ac = wechatUserService.getWechatUserList(activityId);
				RedissonUtils.setBucket(ACTIVITY_PERSONS_KEY + activityId, ac);
			}
			//活动没人参加
			if (CollectionUtils.isEmpty(ac)) {
				LogUtil.error("活动下面没有人");
				return ResultForm.ERROR();
			}
			//第一次
			if (filter.isEmpty()) {
				returnUser = ac.get(0);
				filter.put(returnUser.getOpenid(), returnUser);
				RedissonUtils.setBucket(ACTIVITY_PERSONS_FILTER + activityId, filter);
			}
			Random random = new Random();
			//随机从活动人数中抽取
			while (null == returnUser) {
				int s = random.nextInt(ac.size());
				returnUser = ac.get(s);
				if (null != returnUser) {
					if (!filter.containsKey(returnUser.getOpenid())) {
						filter.put(returnUser.getOpenid(), returnUser);
						RedissonUtils.setBucket(ACTIVITY_PERSONS_FILTER + activityId, filter);
						break;
					}else{
						returnUser = null;
					}
				}
				//抽奖人数 == 中奖人数 ，  不合理
				if (filter.size() == ac.size()) {
					return ResultForm.ERROR();
				}
			}
			if (null == returnUser) {
				LogUtil.error("活动下面没有人");
				return ResultForm.ERROR();
			}
			//输出中奖人
			Map<String, Object> userMap = new HashMap<String, Object>();
			UserInfo userInfo = WeixinHelper.user.info(TokenGetter.getAccessToken(), returnUser.getOpenid());
			LogUtil.debug(JsonUtils.object2Json(userInfo));
			userMap.put("telVal", userInfo.getNickname());
			userMap.put("imgUrl", userInfo.getHeadimgurl());
			userMap.put("openId", DesUtil.encrypt(returnUser.getOpenid()));//openid加密
			return ResultForm.OK().setObject(userMap);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultForm.ERROR("系统异常");
		}

	}

	/**
	 * 通过微信发送图文消息给指定用户
	 * 
	 * @param request
	 * @param activityId
	 * @return
	 */
	@RequestMapping("/sendTextMsg")
	@ResponseBody
	public void sendTextMsg(HttpServletRequest request, String openId, String activityId) {
		WechatActivity activity = wechatActivityDao.getById(activityId);
		if(null==activity){
			LogUtil.error("=======活动为空");
			return;
		}
		String text = "恭喜，您是【" + activity.getActivityName() + "】的幸运用户，请凭通知消息联系工作人员确认！";
		WeixinHelper.messages.sendTextMsg(TokenGetter.getAccessToken(),DesUtil.decrypt(openId), text);
	}
}
